/**
 * 	 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *   @author Colin Redmond
 *   Copyright (C) 2011 Colin Redmond
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package com.cred.industries.platform.view.account {
	
	import com.cred.industries.platform.business.TaskEvent;
	import com.cred.industries.platform.business.facade.CustomerFacade;
	import com.cred.industries.platform.business.facade.SessionFacade;
	import com.cred.industries.platform.business.object.CustomerBO;
	import com.cred.industries.platform.dialog.DialogManager;
	import com.cred.industries.platform.model.Config;
	import com.cred.industries.platform.model.LocalUserData;
	import com.cred.industries.platform.view.account.skin.LoginSkin;
	import com.cred.industries.platform.view.component.DialogBackingAndTitle;
	import com.cred.industries.platform.view.account.events.LoginEvents;
	
	import flash.events.MouseEvent;
	
	import mx.events.FlexEvent;
	import mx.states.State;
	
	import spark.components.Button;
	import spark.components.Label;
	import spark.components.SkinnablePopUpContainer;
	import spark.components.TextInput;
	
	[Event(name="LOGIN_COMPLETE", type="com.cred.industries.view.account.events.LoginEvents")]
	[Event(name="LOGOUT_COMPLETE", type="com.cred.industries.view.account.events.LoginEvents")]
	[Event(name="LOGIN_FAILED", type="com.cred.industries.view.account.events.LoginEvents")]
	
	
	[SkinState("login")]
	[SkinState("wait")]
	[SkinState("create")]
	
	/**
	 * @author Colin Redmond
	 * Copyright 2011
	 **/
	public class Login extends SkinnablePopUpContainer {
		
		[SkinPart(required="true")] public var submitBtn:Button;
		[SkinPart(required="true")] public var backing:DialogBackingAndTitle;
		[SkinPart(required="true")] public var cancelBtn:Button;
		[SkinPart(required="false")] public var createBtn:Button;
		[SkinPart(required="true")] public var personaName:TextInput;
		[SkinPart(required="true")] public var password:TextInput;
		[SkinPart(required="true")] public var firstName:TextInput;
		[SkinPart(required="true")] public var lastName:TextInput;
		[SkinPart(required="true")] public var emailAddress:TextInput;
		[SkinPart(required="true")] public var errorMsg:Label;
		
		private var mSessionFacade:SessionFacade = new SessionFacade();
		private var mCustomerFacade:CustomerFacade = new CustomerFacade();
		
		public function Login() {
			
			if(Config.isMobile()) {
				
				setStyle("skinClass", com.cred.industries.platform.view.account.skin.LoginSkin);
			} else {
				setStyle("skinClass", com.cred.industries.platform.view.account.skin.LoginSkin);
			}
			currentState = "login";
			
			states = [
				new State({name:"login"}),
				new State({name:"wait"}),
				new State({name:"create"})];
			
			addEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler, false, 0, true);
		}
		
		private function creationCompleteHandler(event:FlexEvent):void {
			
			trace("creationCompleteHandler");
			registerListeners();
			
			personaName.setFocus();
		}
		
		private function registerListeners():void {
			
			mCustomerFacade.addEventListener(TaskEvent.TASK_COMPLETE, createComlete, false, 0, true);
			mCustomerFacade.addEventListener(TaskEvent.TASK_FAILED, createFailed, false, 0, true);
			mSessionFacade.addEventListener(TaskEvent.TASK_COMPLETE, loginComlete, false, 0, true);
			mSessionFacade.addEventListener(TaskEvent.TASK_FAILED, loginFailed, false, 0, true);
		}
		
		//with a skin this is call as each movie clip such as title, body ect is added to the 
		//slide. So we need to update the part with the correct value if we have it.
		override protected function partAdded(partName:String, instance:Object) : void {
			
			super.partAdded(partName, instance);
			
			if(instance == submitBtn) {
				
				submitBtn.addEventListener(MouseEvent.CLICK, submitClicked, false, 0, true);
			} else if (instance == backing) {
				backing.closeButton.addEventListener(MouseEvent.CLICK, closeClicked, false, 0, true);
				backing.title.text = "Login";
			} else if (instance == cancelBtn) {
				cancelBtn.addEventListener(MouseEvent.CLICK, closeClicked, false, 0, true);
			}
		}
		
		private function submitClicked(event:MouseEvent):void {
			
			var cust:CustomerBO = new CustomerBO();
			if(currentState == "login") {
				
				cust.personaName = personaName.text;
				cust.password = password.text;
				mSessionFacade.login(cust);
			} else {
				
				cust.personaName = personaName.text;
				cust.password = password.text;
				cust.firstName = firstName.text;
				cust.lastName = lastName.text;
				cust.emailAddress = emailAddress.text;
				mCustomerFacade.createCustomer(cust);
			}
			
			LocalUserData.get().localUser = cust;
			currentState = "wait";
		}
		
		private function closeClicked(event:MouseEvent):void {
			
			dispatchEvent(new LoginEvents(LoginEvents.LOGIN_CANCELED));
		}
		
		private function createClicked(event:MouseEvent):void {
			
			if(currentState == "login")
				currentState = "create";
			else if(currentState == "create")
				currentState = "login";
		}		
		
		private function createComlete(event:TaskEvent):void {
			
			mSessionFacade.login(LocalUserData.get().localUser);
		}
		
		private function createFailed(event:TaskEvent):void {
			DialogManager.alert("Error", "there was an error creating creating your persona, please try again");
			currentState = "login";
		}
		
		private function loginComlete(event:TaskEvent):void {
			
			dispatchEvent(new LoginEvents(LoginEvents.LOGIN_COMPLETE));
		}
		
		private function loginFailed(event:TaskEvent):void {
			errorMsg.text = "The username or password \nyou entered is incorrect.";
			currentState = "login";
		}
	}
}